<?php
namespace App\Api\Controllers;
use Common\ApiController;
use Common\Common;
use Common\Models\BShopCityRegion;
use Common\Models\BShopGoods;
use Common\Models\User;

class TestController extends ApiController
{
    public function initialize()
    {
        parent::initialize();
    }


    public function liveAction(){
        $jsonStr = '{"title":"家乡鸡·营养美食(业州广场超省店)","shopLogo":"https://img.alicdn.com/imgextra/i3/2206620055114/O1CN019gnrTm1neGDMhRudi_!!2206620055114-2-koubei.png","sales":500,"itemUrl":"https://s.click.ele.me/t?&e=-s02Kay6BYphJnfpmYk6movgFdWwd1n4fyqv4TvGij9KNi5qLCFrDsGBNIfmNDXSZAsEuywWUBWF0mzzyzLe5RckM5uA2ajGdLcIS3s2w7hwIOIwr5mjRTcR0RpDdZlagfZtn0OVpIBbdInuvxsoPlQ9xmUGrkT2gqkHUoRC48ZEBS9EMYIlZ739JTIgx36fk7Sfg3a1qqEF8Lnm0qaBHNiDHpf7jIDXfeKvP8lwv5jLuCNIltGwslrWPXQZp3dhiHZpUsaIQIpT0WTNJvlEh38m5fJiw5YTvwjYkOI3bqVrNKXNkSjCBdmrD4He2VuFpxzfH9lub2IBDdpioh2isyeImKU1fOe5a1gKEhcNQogFjo2vSshhefNnLmqAk5vHfizkCw&latitude=30.609138775242243&longitude=109.73159819782256&newRetail=false&union_lens=lensId%3AMAPI%401668232754%40210774c4_0b2c_1846a6bb638_81f9%4001","daySurplusStock":0,"type":1,"deliveryPrice":0,"bonusCent":0,"deliveryFee":"4.0","deliveryType":"0","deliveryTime":"30","deliveryDistance":"2193","serviceRating":"4.8","salesTag":["最高10%","40减10","食无忧"],"shopId":"","activityId":"","bountyMinLimitCent":0,"recommendTips":""}';
        $jsonArr = json_decode($jsonStr,true);
        $responseResult = [];
        for($i=0;$i<9;$i++){
            $responseResult[] = $jsonArr;
        }
        $this->ok($responseResult);
    }


    public function aabAction(){
        $BShopCityRegionDb = new BShopCityRegion();
        $bShopCityRegion = $BShopCityRegionDb->find(array(
            'conditions'=>"level=2",
            'columns'=>"id as citycode,name,pinyin,Lng as lng,Lat as lat"
        ))->toArray();
        foreach ($bShopCityRegion as $key=>$value){
            $bShopCityRegion[$key]['ishot'] = false;
        }
        echo json_encode($bShopCityRegion);
    }



    public function commissionAction(){
        $result = Common::self_CalculatingMoney(22,1);
        $this->ok($result);
//        $result = Common::self_CalculatingMoney(2,10);
//        var_dump($result);
    }






    public function haitaoAction(){
        $this->params['type']=4;
        $result = $this->zhetaoke->api_all_juhuasuan($this->params);
        foreach($result['data'] as $key=>$value){
            $detail_goods = $this->zhetaoke->goods_detail($value['GoodsId']);
            if(!$detail_goods){
                continue;
            }
            $BShopGoodsDb = new BShopGoods();
            $BShopGoodsDb->detailed_img = $detail_goods['PicLogo'];
            $BShopGoodsDb->banner = implode(',',$detail_goods['SmallImages']);
            $BShopGoodsDb->name = $detail_goods['Title'];
            $BShopGoodsDb->describe = $detail_goods['Suggest'];
            $BShopGoodsDb->details = $detail_goods['PicList'] ? implode(',',$detail_goods['PicList']) : implode(',',$detail_goods['SmallImages']);
            $BShopGoodsDb->status = 1;
            $BShopGoodsDb->original_price = $detail_goods['Price'];
            $BShopGoodsDb->discount_price = $detail_goods['EndPrice'];
            $BShopGoodsDb->commission = $detail_goods['Commission'];
            $BShopGoodsDb->stock = $detail_goods['CouponSurplus'];
            $BShopGoodsDb->created_at = date('Y-m-d H:i:s');
            $BShopGoodsDb->updated_at = date('Y-m-d H:i:s');
            $BShopGoodsDb->shop_id = 5;
            $BShopGoodsDb->good_commit_rate = rand(50,100);
            $BShopGoodsDb->goods_commit = rand(60,4000);
            $BShopGoodsDb->admin_status = 1;
            $BShopGoodsDb->is_report = 0;
            $BShopGoodsDb->goods_sn = Common::order_sn("G");
            $BShopGoodsDb->save();
        }
        $this->ok($result);
    }





    public function vphaccesstokenAction(){
//        https://auth.vip.com/oauth2/authorize?client_id=82fd918a&response_type=code&redirect_uri=urn:ietf:wg:oauth:2.0:oob&state=1212&display=mobile
        //登录巨折的号
        $url = 'https://auth.vip.com/oauth2/token?client_id=82fd918a&client_secret=6CC0E49D475E815E525BA07D0083F39D&grant_type=authorization_code&redirect_uri=urn:ietf:wg:oauth:2.0:oob&request_client_ip=121.196.24.202&code=e8ee9c6757b24a6a8c47f131e00150fa';
        //   $url = 'https://auth.vip.com/oauth2/token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&request_client_ip=YOUR_IP&code=CODE 返回值包含access_token';
        var_dump(Common::request_post($url,[]));
    }



    public function testwxAction(){
        $url="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg10.360buyimg.com%2Fn0%2Fjfs%2Ft289%2F187%2F270305007%2F49028%2F2b10ae43%2F5407a8aeN10a1a4fa.jpg&refer=http%3A%2F%2Fimg10.360buyimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1627643154&t=2b8b2d22477280757ce92c59a0d6715f";
        var_dump(urldecode($url));
    }


    public function testAction()
    {
        $data['price'] = 80.00;
        $data['stock'] = 9;
        $data['num']=1;
        $data['sku_ids']="86_90";
        $data['img'] = "http://qn.enshitc.com/1620462844093";
        $data['sku_id'] = 22;
        $data["add_jian_status"] = true;
        $data["goods_id"] = "5_20210508164828306586898";
        $data["goods_name"] = "这是测试商品";
        $data["message"]="";
        $data["pay_type"] = 1;
        $data["all_price"] = 80.00;
        $data["ids_arr"] = [];


        $data1['price'] = 10.00;
        $data1['stock'] = 9;
        $data1['num']=1;
        $data1['sku_ids']="86_90";
        $data1['img'] = "http://qn.enshitc.com/1620462844093";
        $data1['sku_id'] = 0;
        $data1["add_jian_status"] = true;
        $data1["goods_id"] = "5_20210508164828316586895";
        $data1["goods_name"] = "这是测试商品cc";
        $data1["message"]="";
        $data1["pay_type"] = 1;
        $data1["all_price"] = 10.00;
        $data1["ids_arr"] = [];

        $result['order_info'][0] = $data;
        $result['order_info'][1] = $data;
        $result['order_info'][2] = $data1;
        $result['pay_type'] = 3;
        $result['all_price'] = "170.00";
        $result['address_id'] = 5;
//        $result['order_info'] = htmlspecialchars(json_encode($result['order_info']));
//        var_dump($result);
        echo json_encode($result);
    }

    //测试

    /**
     * 系统消息
     */
    public function system_messageAction()
    {
        //当前页数
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $page = CommonController::PAGE;
        } else {
            $page = (int)$this->params['page'];
        }
        //当前条数
        if (!isset($this->params['page_size']) || empty($this->params['page_size'])) {
            $pageSize = CommonController::PAGESIZE;
        } else {
            $pageSize = (int)$this->params['page_size'];
        }
        $message    = new Messages();
        $list       = $message->list_message($this->user_info['id']);
        $paginator  = new PaginatorModel(
            array(
                "data"  => $list,
                "limit" => (int)$pageSize,
                "page"  => (int)$page
            )
        );
        $list_limit = $paginator->getPaginate();
        if ($page > $list_limit->total_pages) {
            $this->fail(400, '没有更多数据');
        }
        $this->ok($list_limit);
    }


    public function FreeGoodsAction()
    {
        $res                        = $this->haodanku->goods_detail($this->params['goods_id']);
        $FreeGoods                  = new FreeGoods();
        $FreeGoods->goods_id        = $res['GoodsId'];
        $FreeGoods->free_price      = $res['EndPrice'];
        $FreeGoods->site            = 'haodanku';
        $FreeGoods->types           = 'free';
        $FreeGoods->title           = $res['Title'];
        $FreeGoods->pic             = $res['PicLogo'];
        $FreeGoods->counts          = 1000;
        $FreeGoods->buyed           = 0;
        $FreeGoods->less            = 1000;
        $FreeGoods->coupon          = $res['CouponMoney'];
        $FreeGoods->price           = $res['EndPrice'];
        $FreeGoods->old_price       = $res['Price'];
        $FreeGoods->send_start_time = date('Y-m-d H:i:s');
        $FreeGoods->status          = 1;
        $FreeGoods->created_at      = date('Y-m-d H:i:s');
        $a                          = $FreeGoods->save();
        $redis_key                  = "free_goods";
        $this->cache->del_cache($redis_key);
        die($a);
    }

    public function IndexAction()
    {
        $a = $this->sms->send();
        var_dump($a);
        echo "remove";
        die;
    }


    public function moneyAction()
    {
        $user = new User();
        $res  = $user->CalculatingMoneyV2(169927, 100);
        var_dump($res);
        die;
        echo 123;
        die;
    }

    public function categoryAction()
    {
        $url            = 'http://v2.api.haodanku.com/super_classify/apikey/juapp';
        $request_result = file_get_contents($url);
        $response       = json_decode($request_result, true);
        if ($response['msg'] == 'SUCCESS') {
            //var_dump($response['general_classify'][0]['data'][1]['info']);
            echo json_encode($response['general_classify']);
        }
    }


    public function web_viewAction()
    {
        $params     = array_merge($this->request->get(), $this->request->getPost());
        $free_goods = new FreeGoods();
        $res        = $free_goods->get_goods($params);
        $res        = array_chunk($res, 2);
        $this->ok($res);
    }


    public function clearAction()
    {
        $this->redis->FLUSHALL();
        die('over');
    }


    /**
     * 测试上传类
     */
    public function file_imgAction()
    {
        if (empty($_FILES)) {
            $this->fail(-1, '请上传图片');
        }
        $img_type = explode('/', $_FILES["avatar"]["type"])[1];
        $filetype = ['jpg', 'jpeg', 'gif', 'bmp', 'png'];
        if (!in_array($img_type, $filetype)) {
            $this->fail(-1, '上传的图片类型错误,请上传jpg,jpeg,gif,bmp,png类型');
        }
        $type      = explode('/', $_FILES["avatar"]["type"])[1];
        $file_path = "/images/" . time() . rand(1000000, 9999999) . '.' . $type;
        $upload    = move_uploaded_file($_FILES["avatar"]["tmp_name"], APP_PATH . '/public' . $file_path);
        if ($upload == 1) {
            $domain         = CommonController::domain();
            $data['avatar'] = $domain . $file_path;
            return $this->ok($data);
        } else {
            return $this->fail('-1', '上传失败');
        }
    }

    public function payAction()
    {
        $path = str_replace('public', "app/plugins/alipay/AopSdk.php", getcwd());
        require_once $path;

        $aop                     = new AopClient ();
        $aop->gatewayUrl         = 'https://openapi.alipay.com/gateway.do';
        $aop->appId              = '2017081208160826';
        $aop->rsaPrivateKey      = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCMxSWEiCrpwcySNdzDa4oCPGWRIZXe73wvwaJeusVUtRi5MuSO7yGVsAA4x6Z01tkOICzBQTS1lR6KC0G9FX0zEb9NojbAcVxuSsGsEJdI9/tNN9lwzYWuWPmrNm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ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB';
        $aop->apiVersion         = '1.0';
        $aop->signType           = 'RSA2';
        $aop->postCharset        = 'UTF-8';
        $aop->format             = 'json';
        $request                 = new AlipayFundTransToaccountTransferRequest ();
        $out_biz_no              = date('YmdHis') . rand(1000, 9999);
        $payee_account           = "18826989806";
        $amount                  = 0.1;
        $payer_real_name         = $payer_show_name = $payee_real_name = '111';
        $payee_real_name         = '熊明明1';
        $remark                  = 'remark';
        $ext_param               = "";
        $request->setBizContent("{" .
            "\"out_biz_no\":\"" . $out_biz_no . "\"," .
            "\"payee_type\":\"ALIPAY_LOGONID\"," .
            "\"payee_account\":\"" . $payee_account . "\"," .
            "\"amount\":\"" . $amount . "\"," .
            "\"payee_real_name\":\"" . $payee_real_name . "\"," .
            "\"remark\":\"" . $remark . "\"," .
            "  }");
        $result = $aop->execute($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode   = $result->$responseNode->code;
        var_dump($result);
        var_dump($result->$responseNode);
        if (!empty($resultCode) && $resultCode == 10000) {
            echo "成功";
        } else {
            echo "失败";
        }
        die;
    }


    /**
     *  网页端测试 微信登录
     */
    public function indexwxAction()
    {
        //触发微信返回code码
        $params = array_merge($this->request->get(), $this->request->getPost());
        if (!isset($params['invite_code']) || empty($params['invite_code'])) {
            echo '<h1>邀请码不能为空</h1>';
            die();
        }
        $this->wx->test($params);
    }

    public function userinfoAction()
    {
        $params = array_merge($this->request->get(), $this->request->getPost());
        var_dump($params);
        $code = $params['code'];    //微信code码
        //获取code码，以获取openid
        $openid_info = $this->wx->gettoken($code);
        if (isset($openid_info['errcode'])) {
            $data = ['code' => 100, 'msg' => '微信授权无效的code码'];
            var_dump($data);
        } else {
            $access_token = $openid_info['access_token'];
            $openid       = $openid_info['openid'];
            $user_info    = $this->wx->getuserinfo($access_token, $openid);
            var_dump($user_info);
        }
    }


    //极光推送测试
    public function jpushAction()
    {
        $alias  = ['2542'];
        $title  = '特权中心数据变动通知！';
        $detail = '前期为方便查看下级存在的会员，特权中心统计数据非实际考核数据，新版特权中心更新后会显示正确考核数据。​​';
        $route  = [
            'type'   => 2,
            'path'   => 'H5',
            'title'  => '消息公告',
            'url'    => 'http://api.jiruanos.com/invite/noticedetail?id=15',
            'data'   => '',
            'notice' => null,
        ];
        $result = $this->jpush->pushmsg($alias, $title, $detail, $route);
        var_dump($result);
        die();
    }

    /**
     * 发送短信
     */
    public function jg_smsAction()
    {
        $phone  = '16602722687';
        $result = $this->jpush->jgsms($phone);
        var_dump($result);
    }

    /**
     * 验证短信
     */
    public function check_smscodeAction()
    {
        $msg_id = $this->params['msg_id'];
        $code   = $this->params['code'];
        $result = $this->jpush->jgcheckcode($msg_id, $code);
        var_dump($result);
        die();
    }


    public function mobpushAction()
    {
        //$name = $this->params['name'];
        //$type = $this->params['type'];
        //$result = $this->mob->getPush($name,$type);

        $params['plats']         = [1, 2];
        $params['iosProduction'] = 0;
        $params['target']        = 1;
        $params['alias']         = ["2542", "1005", "7686"];
        $params['content']       = '测试通知111内容';
        $params['type']          = 2;                  //1广播 2自定义
        $params['customType']    = 'text';

        $route            = [
            'type'   => 1,
            'path'   => 'AwakeMsg',
            'title'  => '我的消息',
            'url'    => '',
            'data'   => '',
            'notice' => null
        ];
        $params['extras'] = ['route' => json_encode($route), 'msgTitle' => '这里是通知标题'];
        $result           = $this->mob->postPush($params, 1);
        var_dump($result);
        die();
    }

    //易赛文件导入
    public function yisaiAction(){
        $file        = $_FILES['file'];

        if ($file['error'] == 4) $this->error('请选择上传excel文件');
        $file_types = explode(".", $file['name']);
        $excel_type = array('xls', 'csv', 'xlsx');

        if (!in_array(strtolower(end($file_types)), $excel_type)) {
            $this->error("不是Excel文件，请重新上传");
        }
        $new_excels_data = $this->excels->testFile($file);
        $yi = new YiSaiProduct();
        $yi->batch_insert($new_excels_data);
    }

    //测试导入excel
    public function importExcelAction()
    {
        $create_file = '../cache/' . date('Y-m-d H:i:s', time()) . '.log';       //创建文件
        $file        = $_FILES['file'];
        if ($file['error'] == 4) $this->error('请选择上传excel文件');
        $file_types = explode(".", $file['name']);
        $excel_type = array('xls', 'csv', 'xlsx');
        if (!in_array(strtolower(end($file_types)), $excel_type)) {
            $this->error("不是Excel文件，请重新上传");
        }
        $new_excels_data = $this->excels->test($file);
        foreach ($new_excels_data as $key => $value) {
            if (empty($value['phone'])) {
                continue;
            }
            $user = new User();
            //            if (strpos($value['nickname'], '.') !== false) {
            //                $data['nickname'] = substr($value['nickname'], strripos($value['nickname'], ".") + 1);       //截取小数点后面的字符
            //            } else {
            //                if ($value['nickname'] != 0) {
            //                    $data['nickname'] = substr($value['nickname'], strripos($value['nickname'], (int)$value['nickname']) + 1);       //截取小数点后面的字符
            //                } else {
            //                    $data['nickname'] = $value['nickname'];
            //                }
            //            }
            //            $data['nickname'] = trim($data['nickname']);
            $data['phone'] = $value['phone'];

            $is_user = $user->find_by_phone($value['phone']);       //查看当前记录是否已经导入了
            if (empty($is_user)) {
                if (!empty($value['referer_phone'])) {           //存在上级手机号
                    $parent_user = $user->find_by_phone($value['referer_phone']);
                    if ($parent_user) {                                    //存在上级手机号，但是没有找到上级
                        $data['referer_id'] = $parent_user['id'];
                        if ($parent_user['path'] == '') {
                            $data['path'] = $parent_user['referer_id'];
                        } else {
                            $data['path'] = $parent_user['path'] . ',' . $parent_user['referer_id'];
                        }
                    } else {
                        $write = json_encode($new_excels_data[$key]) . "-----写入失败-没有找到上级用户\n";
                        file_put_contents($create_file, $write, FILE_APPEND | LOCK_EX);
                        continue;
                    }
                } else {                                          //不存在上级手机号
                    $data['referer_id'] = 0;
                    $data['path']       = '';
                }
                $invitecode           = new InviteCodes();
                $data['invite_code']  = $invitecode->usedInviteCode();       //创建邀请码
                $data['is_appuser']   = 0;
                $data['admin_status'] = 1;
                $result               = $user->save_user($data);
                if ($result) {
                    $write = json_encode($new_excels_data[$key]) . "-----写入成功\n";
                    file_put_contents($create_file, $write, FILE_APPEND | LOCK_EX);
                } else {
                    $write = json_encode($new_excels_data[$key]) . "-----写入失败-保存数据库的时候\n";
                    file_put_contents($create_file, $write, FILE_APPEND | LOCK_EX);
                }
            } else {
                $write = json_encode($new_excels_data[$key]) . "-----记录已经存在\n";
                file_put_contents($create_file, $write, FILE_APPEND | LOCK_EX);
            }

        }
    }



    public function updateparentAction()
    {
        set_time_limit(0);
        $referer_phone = $this->params['referer_phone'];
        if (!isset($referer_phone) || empty($referer_phone)) {
            $this->fail(-1, '上级号码不能为空');
        }
        $phone = trim($this->params['phone']);
        //$create_file = '../cache/update_'.$phone.'.log';       //创建文件
        if (!isset($phone) || empty($phone)) {
            $this->fail(-1, '当前要修改的手机号不能为空');
        }


        $create_file = '../cache/update_' . $phone . '.log';       //创建文件
        $user        = new User();
        $parent_user = $user->find_by_phone($referer_phone);        //父级手机号码
        if ($parent_user) {
            $is_user = $user->find_by_phone($phone);
            if ($is_user) {
                $this->child_cloumns($phone, $referer_phone);
            } else {
                $write = $phone . "----用户信息没有找到\n";
                file_put_contents($create_file, $write, FILE_APPEND | LOCK_EX);
                $this->fail(-1, '用户信息没有找到');
            }
        } else {
            $write = $referer_phone . "----没有找到上级号码\n";
            file_put_contents($create_file, $write, FILE_APPEND | LOCK_EX);
            $this->fail(-1, '没有找到上级号码');
        }
    }


    //找用户的下级 $id最顶级需要修改的id
    public function child_cloumns($phone, $referer_phone, $path = '')
    {
        //$create_file = '../cache/update_'.$phone.'.log';       //创建文件
        $user                  = new User();
        $referer_user          = $user->find_by_phone($referer_phone);   //父级用户
        $is_user               = $user->find_by_phone($phone);                //用户
        $path                  = $referer_user['path'] . ',' . $referer_user['referer_id'];
        $referer_id            = $referer_user['id'];
        $is_user['path']       = $path;
        $is_user['referer_id'] = $referer_id;
        $result                = $user->save_user($is_user);
        if ($result) {
            $write = $phone . "----修改成功--referer_id:$referer_id---path:$path\n";
            echo $write;
        }
        $res = $user::find(array(
            $conditions = "referer_id = " . $is_user['id'],
        ));
        $res = CommonController::transition_array($res);
        if ($res) {
            foreach ($res as $key => $value) {
                $user         = new User();
                $child_parent = $user->find_by_firstId($value['referer_id']);
                $this->child_cloumns($value['phone'], $child_parent['phone'], $referer_user['path']);
            }
        }
    }


    /**
     * @return
     */
    public function invite_codenoAction()
    {

        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0, 25)]
            . strtoupper(dechex(date('m')))
            . date('d')
            . substr(time(), -5)
            . substr(microtime(), 2, 5)
            . sprintf('%02d', rand(0, 99));
        for (
            $a = md5($rand, true),
            $s = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
            $d = '',
            $f = 0;
            $f < 6;
            $g = ord($a[$f]),
            $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],
            $f++
        ) ;
        $user          = new User();
        $is_invitecode = $user->find_by_inviteCode($d);
        if ($is_invitecode) {
            $this->createinvite();
        }
        return $d;


    }


    public function haibaoAction()
    {
        //案例一：将活动背景图片和动态二维码图片合成一张图片
        //图片一
        $path_1 = 'http://jzcloud.jiruan.ltd/ic-j.png'; //海报
        //图片二
        $path_2 = 'http://jr.4578.net/img/avatar1.png'; //头像
        //案例二：将活动背景图片设置透明，然后和动态二维码图片合成一张图片
        // 图片一
        //创建图片对象
        $image_1 = imagecreatefrompng($path_1);
        $image_2 = imagecreatefrompng($path_2);
        //创建真彩画布
        //imagecreatetruecolor(int $width, int $height)--新建一个真彩色图像
        $image_3 = imageCreatetruecolor(imagesx($image_1), imagesy($image_1));
        //为真彩画布创建白色背景
        //imagecolorallocate(resource $image, int $red, int $green, int $blue)
        $color = imagecolorallocate($image_3, 255, 255, 255);
        //imagefill(resource $image ,int $x ,int $y ,int $color)
        //在 image 图像的坐标 x，y（图像左上角为 0, 0）处用 color 颜色执行区域填充（即与 x, y 点颜色相同且相邻的点都会被填充）
        imagefill($image_3, 0, -0, $color);
        //设置透明
        //imagecolortransparent(resource $image [,int $color])
        //将image图像中的透明色设定为 color
        imageColorTransparent($image_3, $color);
        //复制图片一到真彩画布中（重新取样-获取透明图片）
        //imagecopyresampled(resource $dst_image ,resource $src_image ,int $dst_x ,int $dst_y ,int $src_x , int $src_y ,int $dst_w ,int $dst_h ,int $src_w ,int $src_h)
        // dst_image:目标图象连接资源
        // src_image:源图象连接资源
        // dst_x:目标 X 坐标点
        // dst_y:目标 Y 坐标点
        // src_x:源的 X 坐标点
        // src_y:源的 Y 坐标点
        // dst_w:目标宽度
        // dst_h:目标高度
        // src_w:源图象的宽度
        // src_h:源图象的高度
        imagecopyresampled($image_3, $image_1, 0, 0, 0, 0, imagesx($image_1), imagesy($image_1), imagesx($image_1), imagesy($image_1));
        //与图片二合成
        //imagecopymerge ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h , int $pct )---拷贝并合并图像的一部分
        // //将 src_im 图像中坐标从 src_x，src_y 开始，宽度为 src_w，高度为 src_h 的一部分拷贝到 dst_im 图像中坐标为 dst_x 和 dst_y 的位置上。两图像将根据 pct 来决定合并程度，其值范围从 0 到 100。当 pct = 0 时，实际上什么也没做，当为 100 时对于调色板图像本函数和 imagecopy() 完全一样，它对真彩色图像实现了 alpha 透明。
        imagecopymerge($image_3, $image_2, 265, 440, 0, 0, imagesx($image_2), imagesy($image_2), 100);
        // 输出合成图片
        var_dump(imagepng($image_3, '../cache/merge1.png'));
    }




    public function ceshi_avAction()
    {
        $url  = 'http://api.jiruanos.com/web_view/goweb?avid=1585018034441_new';
        $url1 = 'http://api.jiruanos.com/web_view/goweb?avid=';
        if (strpos($url, $url1) !== false) {
            $avid = explode($url1, $url)[1];
            //$redis_key1='user_'.$user_info['id'].$avid;
            //$cache_av=$cache->get_cache($redis_key1);
            $cache_av = [];
            if (!$cache_av) {
                if (strpos($avid, '_new') !== false) {
                    $avid = substr($avid, 0, strlen($avid) - 4);
                    var_dump($avid);
                    echo 'new';
                    //$request = $this->taobao->activitylink_new($avid,$user_info['tb_rid']);
                } else {
                    echo 'old';
                    //$request = $this->taobao->activitylink($avid, $user_info['tb_rid']);
                }
            }
        }
    }


    /**
     * 专属口令
     */
    public function exclusive_codeAction()
    {
        if (!isset($this->params['old_invite_code']) || empty($this->params['old_invite_code'])) {
            $this->fail(-1, '原来的邀请码不能为空');
        }
        if (!isset($this->params['new_invite_code']) || empty($this->params['new_invite_code'])) {
            $this->fail(-1, '新的邀请码不能为空');
        } else {
            if (!is_numeric($this->params['new_invite_code'])) {
                $this->fail(-1, '新的邀请码必须是数字');
            }
            if (strlen(strlen($this->params['new_invite_code'])) > 6) {
                $this->fail(-1, '必须小于六位数');
            }
        }
        $users_obj  = new User();
        $old_invite = $users_obj->find_by_inviteCode($this->params['old_invite_code']);
        if (empty($old_invite)) {
            $this->fail(-1, '根据原来的邀请码没有找到用户');
        } else {
            if ($old_invite['exclusive_code']) {
                $this->fail(-1, '要设置的字段已经有设置了');
            }
        }
        $new_invite = $users_obj->find_by_inviteCode($this->params['new_invite_code']);
        if ($new_invite) {
            $this->fail(-1, '新设置的邀请码已经别占用');
        }
        $user        = new User();
        $update_user = $user->findFirstById($old_invite['id']);
        //$code1=str_pad($this->params['new_invite_code'],6,"0",STR_PAD_LEFT);      //不足6位前面补0
        $update_user->exclusive_code = $this->params['new_invite_code'];
        if ($update_user->save()) {
            $invite_obj  = new InviteCodes();
            $find_invite = $invite_obj->findFirstById($this->params['new_invite_code']);
            if ($find_invite) {
                $find_invite->used       = 1;
                $find_invite->created_at = date('Y-m-d H:i:s');
                $find_invite->updated_at = date('Y-m-d H:i:s');
                $find_invite->save();
            }
            $this->ok([]);
        } else {
            $this->fail(-1, '设置失败');
        }


    }


    public function linktestAction(){
        $cj_decode = '7G+G0dlLohiOnA+NFjoZ5fNrN+4/6kDDuU7mfq1CpTim4KRSGmqUMgm7tPTH81cn';
        $aesmcrypt = new AESMcrypt();
        $cj_str = $aesmcrypt->decrypt($cj_decode);
        var_dump($cj_str);
    }



    public function peoplesumAction(){
        $conditions = "is_count=0";
        $user = new User();
        $list = $user->find(array(
            $conditions,
            'limit'=>'1000',
        ));
        foreach($list as $key=>$value){
            if($value->path == 0 && $value->path == '') {
                if($value->referer_id != 0 ) {
                    $path = '0,' . $value->referer_id;
                }else{
                    $path = $value->referer_id;
                }
                $pathArr = explode(',', $path);
                //array_push($pathArr, $this->user_info['referer_id']);
            }else{
                $path = $value->path.','.$value->referer_id;
                $pathArr[0] = $path;
            }
            $path = implode(',', $pathArr);
            //直属粉丝数
            $data['start_end_time'] = 0;
            $directCount=$user->getDirectFansCount($value->id,$data);
            //团队粉丝数
            $indirectCount=$user->getIndirectFansCount($value->id,$path);
            $value->direct_vip=$directCount;
            $value->indirect_vip=$indirectCount;
            $value->team_scale=$directCount+$indirectCount;
            $value->is_count=1;
            $value->save();
            echo "成功";
        }


    }



    public function chengjuanAction(){
        $cj = new Cj();
        $h_params['order_sn']='KMZC2020043099525557';
        $result = $cj->orderquery_zc($h_params);
        var_dump($result);
    }


    public function getinvitecodeAction(){
        $url = 'pinduoduo://com.xunmeng.pinduoduo?resource_type=4&method=gen';
        $arr = parse_url($url);
        $queryParts = explode('&', $arr['query']);
        $params = array();
        foreach ($queryParts as $param)
        {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }
        return $params;
    }
    
    
    //获取七牛上传token
    public function gettokenAction(){
        $token = $this->qiniu->get_token();
        $this->ok(['token'=>$token]);
    }


    /**
     * 早晚安问候
     */
    public function get_salutation_dataAction(){
        if(!isset($this->params['page']) || empty($this->params['page'])){
            $this->params['page']=1;
        }

        if(!isset($this->params['page_size']) || empty($this->params['page_size'])){
            $this->params['page_size']=50;
        }

        //分类：1.早安问候；2.用餐问候；3.晚安问候；4.群内公告；5.节日问候；6.爆笑段子；7.其他
        if(!isset($this->params['category']) || empty($this->params['category'])){
            $this->params['category']=5;
        }

        $result = $this->haodanku->get_salutation_data($this->params);
        if($result['code']){
            foreach($result['data']['data'] as $key=>$value){
                $article = new Article();
                $is_exit = $article->find_first_by_images($value['imgsrc']);
                if(!$is_exit){
                    $article = new Article();
                    $article->article_category_id=3;
                    $article->author='买购官方';
                    $article->title=$value['content'];
                    $article->content=$value['content'];
                    $article->images=$value['imgsrc'];
                    $article->published=1;
                    $article->sort=10;
                    $article->created_at=date('Y-m-d H:i:s');
                    $article->updated_at=date('Y-m-d H:i:s');
                    $article->share_num=$value['likenum'];
                    $article->save();
                }
                continue;
            }
            $this->ok($result['data']);
        }else{
            $this->fail(-1,$result['data']);
        }
    }



    /**
     * 精选文案
     */
    public function excellent_editorAction(){
        if(!isset($this->params['page']) || empty($this->params['page'])){
            $this->params['page']=1;
        }

        if(!isset($this->params['page_size']) || empty($this->params['page_size'])){
            $this->params['page_size']=50;
        }
        $result = $this->haodanku->excellent_editor($this->params);
        if($result['code']){
            foreach($result['data']['data'] as $key=>$value){
                $result['data']['data'][$key]['copy_text']=htmlspecialchars_decode($value['copy_text']);
                $result['data']['data'][$key]['images']=$value['itempic'].','.$value['itempic_copy'];
                $article_faquan = new ArticleFaquan();
                $is_exit = $article_faquan->find_first_by_itemid($value['itemid']);
                if(!$is_exit){
                    $article_faquan->itempic=$value['itempic'].','.$value['itempic_copy'];
                    $article_faquan->content=base64_encode(htmlspecialchars_decode($value['copy_text']));
                    $article_faquan->itemid=$value['itemid'];
                    $article_faquan->cateid=0;
                    $article_faquan->save();
                }
            }
            $this->ok($result['data']);
        }else{
            $this->fail(-1,$result['data']);
        }



    }


}
